<template>
  <div>
    <div style="display: flex;justify-content: space-between; width: 100%">
      <el-form
        :model="formData"
        label-position="left"
        label-width="100px"
        :rules="ruleForm"
        ref="ruleForm"

      >
        <el-form-item label="景区选择" prop="scenic_id">
          <el-select v-model="formData.scenic_id" clearable placeholder="请选择景区">
            <el-option
              v-for="item of scenicList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="景点类型" prop="scenic_item_type_id">
          <el-select v-model="formData.scenic_item_type_id" @change="handleScenicType" clearable placeholder="请选择景点类型">
            <el-option
              v-for="item of scenicSpotTypeList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="景点名称" prop="name">
          <el-input v-model="formData.name" style="width: 200px" type="text" placeholder="请输入景点名称"/>
        </el-form-item>
        <el-form-item label="景点地址" prop="address" >
          <el-input v-model="formData.address" style="width: 500px" type="text" placeholder="可从地图上搜索地点"/>
          <div class="amap-wrapper">
            <el-amap-search-box class="search-box" :search-option="searchOption" :on-search-result="onSearchResult"
            ></el-amap-search-box>
            <el-amap vid="amap" :zoom="zoom" :center="center" class="amap-demo" :events="events">
              <el-amap-marker v-for="(marker, index) in markers" :vid="index"
                              :position="marker.position" :events="marker.events"
                              animation="AMAP_ANIMATION_DROP"
              ></el-amap-marker>
              <el-amap-marker ref="Marker" v-for="(marker, index) in addMarkers" :vid="index"
                              :position="marker.position" :events="marker.events"
                              animation="AMAP_ANIMATION_DROP"
              ></el-amap-marker>
            </el-amap>
          </div>
        </el-form-item>
        <el-form-item v-if="all_show" label="景点简介" prop="intro">
          <el-input v-model="formData.intro" style="width: 400px" type="textarea" placeholder="请输入简介"/>
        </el-form-item>
        <el-form-item v-if="all_show" label="景点图片" prop="img">
          <el-upload
            action="https://up.qiniup.com"
            :class="formData.img && formData.img.length > 0 ? 'hidden':''"
            :limit="1"
            :data="uploadData"
            accept="image/*"
            :file-list="formData.img"
            list-type="picture-card"
            :before-upload="beforeAvatarUpload"
            :on-success="upSuccess"
            :on-exceed="overMax"
            :on-remove="handleRemove"
          >
            <i slot="default" class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="">
          </el-dialog>
        </el-form-item>
        <el-form-item v-if="all_show" label="音频文件" prop="media_url">
          <el-upload
            class="upload-demo"
            :limit="1"
            action="https://up.qiniup.com"
            :data="uploadData"
            accept="audio/*"
            :before-upload="beforeAvatarUpload"
            :on-success="(response,file,fileList) => {upSuccess(response,file,fileList,'audio')}"
            :on-remove="(file,fileList) => {handleRemove(file,fileList,'audio')}"
            :on-exceed="() => { $message.warning({ message: '上传音频最大为1' }) }"
            :file-list="formData.media_url"
          >
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item v-if="all_show" label="跳转网址" prop="url">
          <el-input v-model="formData.url" style="width: 200px" type="text" placeholder="请输入网址"/>
        </el-form-item>
        <el-form-item v-if="all_show" label="详情内容" prop="content_html">
          <Tinymce v-model="formData.content_html" :height="300"/>
        </el-form-item>
      </el-form>
    </div>
    <div style="margin: 5% 0 0 5%;">
      <el-button plain style="margin-right: 3%;" @click="$emit('close')">取消</el-button>
      <el-button type="primary" @click="handleChangeStudentInfo">保存</el-button>
    </div>
  </div>
</template>

<script>
import TableMixins from '@/components/WxTables/mixins'
import Tinymce from '@/components/Tinymce/Tinymce'
import { tourScenicGetListByCon, tourScenicItemTypeGetListByCon } from '@/api/scenic'

export default {
  name: 'CommodityInfo',
  components: {
    Tinymce
  },
  mixins: [TableMixins],
  props: {
    formData: {
      type: Object
    }
  },
  data() {
    return {
      tags: [],
      inputVisible: false,
      all_show: false,
      inputValue: '',
      qiNiuToken: '',
      ruleForm: {
        scenic_id: [
          { required: true, message: '请填写景区选择', trigger: 'blur' }
        ],
        scenic_item_type_id: [
          { required: true, message: '请填写景点类型', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请填写景点名称', trigger: 'blur' }
        ],
        address: [
          { required: true, message: '请填写景点地址', trigger: 'blur' }
        ],
        intro: [
          { required: true, message: '请填写景点简介', trigger: 'blur' }
        ],
        img: [
          { required: true, message: '请填加景点图片', trigger: 'blur' }
        ],
        content_html: [
          { required: true, message: '请填写详情内容', trigger: 'blur' }
        ],
      },
      parentIndex: 0,
      editIsAdd: '',
      isType: '',
      dialogImageUrl: '',
      dialogVisible: false,
      disabled: false,
      addParentsList: {
        relationship: '',
        name: '',
        tel_num: '',
        img: ''
      },
      imageUrl: '',
      parentsIndex: 0,
      editJanitor: false,
      select_dept: [],
      scenicList: [],
      scenicSpotTypeList: [],

      //地图参数
      zoom: 11,
      center: [121.006725,29.144079],
      markers: [],
      addMarkers: [],
      searchOption: {
        city: '天台县',
        citylimit: false
      },
      events: {
        click: (e) => {
          this.getPosition(e)
        }
      }
    }
  },
  created() {
    this.firstLoad = false
    this.tags = this.formData.label_arr
    this.getScenicList()
    this.getScenicSpotTypeList()
    if(this.formData.lon && this.formData.lat) {
      const item_obj = {
        position: [this.formData.lon, this.formData.lat]
      }
      this.addMarkers.push(item_obj)
    }
  },
  methods: {
    /**
     * 获取景区列表
     */
    getScenicList() {
      tourScenicGetListByCon({ town_id: this.town_id, level: 'label' }).then(res => {
        this.scenicList = res.data.data
      })
    },
    /**
     * 获取景点列表
     */
    getScenicSpotTypeList() {
      tourScenicItemTypeGetListByCon({ town_id: this.town_id }).then(res => {
        this.scenicSpotTypeList = res.data.data
        if(this.formData.scenic_item_type_id) {
          const change_list = this.scenicSpotTypeList.filter(res=> res.id === this.formData.scenic_item_type_id)
          this.all_show = change_list[0].type === 1 ? true : false
        }
      })
    },
    /**
     * 选择景点类型
     */
    handleScenicType(e) {
      const change_list = this.scenicSpotTypeList.filter(res=> res.id === e)
      this.all_show = change_list[0].type === 1 ? true : false
    },
    /**
     * 监控上传数量
     */
    overMax() {
      this.$message.warning({ message: '上传图片最大为1张' })
    },
    /**
     * 得到上传成功的文件
     * @param fileList
     * @param type
     */
    getFile(fileList, type) {
      if(type) {
        this.$set(this.formData,'media_url',fileList)
      }else{
        this.$set(this.formData,'img',fileList)
      }
    },
    /**
     * 删除图片
     * @param fileList
     * @param type
     */
    deleteFile(fileList,type) {
      if(type) {
        this.$set(this.formData,'media_url',fileList)
      }else{
        this.$set(this.formData,'img',fileList)
      }
    },
    /**
     * 获取地理位置
     * @param e
     */
    getPosition(e) {
      let self = this
      this.addMarkers = []
      const { lat, lng } = e.lnglat
      this.formData.lon =  lng
      this.formData.lat =  lat
      const item_obj = {
        position: [lng, lat]
      }
      new AMap.service('AMap.Geocoder', function() {
        let geocoder = new AMap.Geocoder({})
        geocoder.getAddress(item_obj.position, (status, result)=> {
          if (status === 'complete' && result.info === 'OK') {
            const address = result.regeocode.formattedAddress
            self.$set(self.formData,'address',address)
          }
        })
      })
      this.addMarkers.push(item_obj)
    },
    /**
     * 搜索地图点位
     * @param pois
     */
    onSearchResult(pois) {
      let latSum = 0
      let lngSum = 0
      if (pois.length > 0) {
        pois.forEach(poi => {
          let { lng, lat } = poi
          lngSum += lng
          latSum += lat
        })
        let center = {
          lng: lngSum / pois.length,
          lat: latSum / pois.length
        }
        this.center = [center.lng, center.lat]
      }
    },
    showInput() {
      this.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    handleIsAdd(type, index) {
      this.editIsAdd = type
      this.parentIndex = index
      if (type === 'create') {
        this.isType = '添加'
        this.addParentsList = {}
      }
      if (type === 'edit') {
        this.isType = '编辑'
        this.addParentsList = JSON.parse(JSON.stringify(this.formData.parents[index]))
      }
      this.editJanitor = true
    },
    beforeAddAvatarUpload(file) {
      uploadNormalFile(file, (res) => {
        this.$set(this.addParentsList, 'img', res)
      })
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    /**
     * 保存
     */
    handleChangeStudentInfo() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          let list = JSON.parse(JSON.stringify(this.formData))
          if (this.formData.img && this.formData.img.length) {
            list.img = this.formData.img.map(item => {
              return item.name ? this.img_url + item.response.key : this.img_url + item.uid
            })
          }
          if(this.formData.media_url && this.formData.media_url.length){
            list.media_url = this.formData.media_url.map(item => {
              return item.type === 0 ? this.img_url + item.uid : this.img_url + item.response.key
            })
          }
          if(!this.all_show) {
            list.content_html = ''
            list.intro = ''
            list.url = ''
            list.img = []
            list.media_url = []
          }
          this.$emit('saveFrom', list)
        } else {
          return false
        }
      })
    }
  }
}
</script>
<style scoped>
.amap-wrapper {
  height: 24rem;
  margin-top: 8px;
}

.amap-demo {
  height: 100%;
}

.search-box {
  position: absolute;
  top: 56px;
  left: 4px;
}

.amap-page-container {
  position: relative;
}

.el-tag + .el-tag {
  margin-left: 10px;
}

.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}

.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}

.time_title {
  font-size: 14px;
  color: #606266;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.hidden >>> .el-upload--picture-card {
  display: none;
}
</style>
<style lang="scss" src="./style/Form.scss" scoped>

</style>
